/**
 * FormConfig.java
 * Copyright (C) 2009 Jose Mauro da Silva Sandy
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 * FormConfig.java
 *
 * Created on 09/08/2009, 11:15:36
 */

package frames;

import java.io.*;
import java.util.Properties;
import javax.swing.JOptionPane;
import utils.ApplicationPath;

/**
 *
 * @author jmsandy
 */
public class FormConfig extends javax.swing.JDialog {

    //<editor-fold defaultstate="collapsed" desc="Constructors">
    /** Creates new form FormConfig */
    public FormConfig() {
        initComponents();
        initializeMyComponents();
    }
    //</editor-fold>

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FormConfig().setVisible(true);
            }
        });
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelPrinc = new javax.swing.JPanel();
        lbNomeUsuario = new javax.swing.JLabel();
        textNomeUsuario = new javax.swing.JTextField();
        lbSenha = new javax.swing.JLabel();
        textSenha = new javax.swing.JPasswordField();
        lbEndereco = new javax.swing.JLabel();
        textEndereco = new javax.swing.JTextField();
        lbNomeBase = new javax.swing.JLabel();
        textNomeBase = new javax.swing.JTextField();
        lbPorta = new javax.swing.JLabel();
        textPorta = new javax.swing.JFormattedTextField();
        panelBotoes = new javax.swing.JPanel();
        btnConfirmar = new javax.swing.JButton();
        btnReboot = new javax.swing.JButton();

        setTitle("Configurações da Conexão com o Banco de Dados");
        setFont(new java.awt.Font("Monospaced", 0, 12));
        setName("formConexao"); // NOI18N
        setResizable(false);

        panelPrinc.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Configurações", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Monospaced", 0, 12))); // NOI18N

        lbNomeUsuario.setFont(new java.awt.Font("Monospaced", 0, 12));
        lbNomeUsuario.setText("Nome do Usuário");

        textNomeUsuario.setFont(new java.awt.Font("Monospaced", 0, 12));
        textNomeUsuario.setToolTipText("Nome do Usuário");

        lbSenha.setFont(new java.awt.Font("Monospaced", 0, 12));
        lbSenha.setText("Senha");

        textSenha.setFont(new java.awt.Font("Monospaced", 0, 12));
        textSenha.setToolTipText("Senha do Usuário");

        lbEndereco.setFont(new java.awt.Font("Monospaced", 0, 12));
        lbEndereco.setText("Endereço Base de Dados");

        textEndereco.setFont(new java.awt.Font("Monospaced", 0, 12));
        textEndereco.setToolTipText("Endereço da Base de Dados");

        lbNomeBase.setFont(new java.awt.Font("Monospaced", 0, 12));
        lbNomeBase.setText("Nome da Base de Dados");

        textNomeBase.setFont(new java.awt.Font("Monospaced", 0, 12));
        textNomeBase.setToolTipText("Nome da Base de Dados");

        lbPorta.setFont(new java.awt.Font("Monospaced", 0, 12));
        lbPorta.setText("Porta de Conexão");

        try {
            textPorta.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        textPorta.setToolTipText("Porta de Conexão");
        textPorta.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);
        textPorta.setFont(new java.awt.Font("Monospaced", 0, 12));

        javax.swing.GroupLayout panelPrincLayout = new javax.swing.GroupLayout(panelPrinc);
        panelPrinc.setLayout(panelPrincLayout);
        panelPrincLayout.setHorizontalGroup(
            panelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelPrincLayout.createSequentialGroup()
                .addGroup(panelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelPrincLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(panelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lbEndereco)
                            .addComponent(lbNomeBase)
                            .addComponent(lbPorta))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(panelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(textEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, 274, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(textNomeBase, javax.swing.GroupLayout.PREFERRED_SIZE, 274, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(textPorta, javax.swing.GroupLayout.PREFERRED_SIZE, 274, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelPrincLayout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addGroup(panelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lbNomeUsuario)
                            .addComponent(lbSenha))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(panelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(textSenha, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE)
                            .addComponent(textNomeUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 315, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );

        panelPrincLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {textEndereco, textNomeBase, textPorta});

        panelPrincLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {textNomeUsuario, textSenha});

        panelPrincLayout.setVerticalGroup(
            panelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelPrincLayout.createSequentialGroup()
                .addGroup(panelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbNomeUsuario, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(textNomeUsuario, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lbSenha)
                    .addComponent(textSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbEndereco, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(textEndereco, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbNomeBase, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(textNomeBase, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbPorta, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(textPorta, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        panelPrincLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {textNomeUsuario, textSenha});

        panelPrincLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {textEndereco, textNomeBase, textPorta});

        panelBotoes.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        panelBotoes.setFont(new java.awt.Font("Monospaced", 0, 12));

        btnConfirmar.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnConfirmar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ok.png"))); // NOI18N
        btnConfirmar.setText("Confirmar");
        btnConfirmar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnConfirmarMouseClicked(evt);
            }
        });

        btnReboot.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnReboot.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/reboot.png"))); // NOI18N
        btnReboot.setText("Reiniciar");
        btnReboot.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnRebootMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout panelBotoesLayout = new javax.swing.GroupLayout(panelBotoes);
        panelBotoes.setLayout(panelBotoesLayout);
        panelBotoesLayout.setHorizontalGroup(
            panelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelBotoesLayout.createSequentialGroup()
                .addContainerGap(117, Short.MAX_VALUE)
                .addComponent(btnConfirmar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnReboot, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(109, 109, 109))
        );
        panelBotoesLayout.setVerticalGroup(
            panelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBotoesLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnConfirmar)
                    .addComponent(btnReboot))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(panelBotoes, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(panelPrinc, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelPrinc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(panelBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(51, 51, 51))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-504)/2, (screenSize.height-285)/2, 504, 285);
    }// </editor-fold>//GEN-END:initComponents

    //<editor-fold defaultstate="collapsed" desc="Events">
    private void btnConfirmarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnConfirmarMouseClicked
        // Verifica a confirmacao
        if(JOptionPane.showConfirmDialog(this, "Confirma a alteração?",
                       "Confirmation", JOptionPane.OK_CANCEL_OPTION,
                       JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION){
            
            StringBuilder builder = validateFields();
            if(builder == null){

                if(updateFile()){
                    showMessageConfirmation("Alteração realizada com sucesso!");
                }
                else{
                    showMessageError("Erro ao modificar o arquivo!");
                }
            }
            else{
                showMessageError(builder.toString());
            }
        }
    }//GEN-LAST:event_btnConfirmarMouseClicked

    private void btnRebootMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnRebootMouseClicked
        // Verifica a confirmacao
        if(JOptionPane.showConfirmDialog(this, "Confirma a reinicialização?",
                       "Confirmation", JOptionPane.OK_CANCEL_OPTION,
                       JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION){
            if(rebuildFile()){
                showMessageConfirmation("Reinicialização realizada com sucesso!");
            }
            else{
                showMessageError("Erro ao modificar o arquivo!");
            }
        }

    }//GEN-LAST:event_btnRebootMouseClicked
    //</editor-fold>

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConfirmar;
    private javax.swing.JButton btnReboot;
    private javax.swing.JLabel lbEndereco;
    private javax.swing.JLabel lbNomeBase;
    private javax.swing.JLabel lbNomeUsuario;
    private javax.swing.JLabel lbPorta;
    private javax.swing.JLabel lbSenha;
    private javax.swing.JPanel panelBotoes;
    private javax.swing.JPanel panelPrinc;
    private javax.swing.JTextField textEndereco;
    private javax.swing.JTextField textNomeBase;
    private javax.swing.JTextField textNomeUsuario;
    private javax.swing.JFormattedTextField textPorta;
    private javax.swing.JPasswordField textSenha;
    // End of variables declaration//GEN-END:variables

    //<editor-fold defaultstate="collapsed" desc="Methods">
    // Messagem de erro
    private void showMessageError(String msg){
        JOptionPane.showMessageDialog(this, msg, "Configuração",
                                                    JOptionPane.ERROR_MESSAGE);
    }

    // Messagem de alerta
    private void showMessageConfirmation(String msg){
        JOptionPane.showMessageDialog(this, msg, "Configuração",
                                               JOptionPane.INFORMATION_MESSAGE);
    }

    // Recupera as informacoes correntes de configuracao do arquivo
    private void initializeMyComponents(){
        try {

           Properties properties = new Properties();
           File file = new File(ApplicationPath.getApplicationPath() +
                                 "properties.properties");
           properties.load(new FileInputStream(file));

           textNomeUsuario.setText(properties.getProperty("user"));
           textSenha.setText(properties.getProperty("password"));
           String url = properties.getProperty("url");
           textEndereco.setText(url.split(":")[0].toString().trim());
           textNomeBase.setText(url.split("/")[1].toString().trim());
           textPorta.setText(url.split(":")[1].toString().split("/")[0]);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Altera com as informacoes recebidas
    private boolean updateFile(){
        boolean flag = true;

        try{
            Properties props = new Properties(); // Objeto arquivo .properties

            // Definindo cabecalho Padrao do Arquivo
            StringBuilder builder = new StringBuilder();
            builder.append("Armazena as informacoes de conexao do sistema ");
            builder.append("para acesso ao banco \r\n");
            String s = utils.Encrypt.encryptPassword(textSenha.getPassword());

            // Setando os novos atributos
            props.setProperty("user", textNomeUsuario.getText().trim());
            props.setProperty("password", s);
            props.setProperty("url", textEndereco.getText().trim() + ":" +
              textPorta.getText().trim() + "/" + textNomeBase.getText().trim());

            // Gravando o nome arquivo
            props.store(new FileOutputStream(
            new File(ApplicationPath.getApplicationPath() +
                    "properties.properties")), builder.toString());
        }
        catch(Exception e){
            e.printStackTrace();
            flag = false;
        }

        return flag;
    }

    // Reinicia o arquivo para o estado padrao
    private boolean rebuildFile(){
        boolean flag = true;

        try{
            Properties props = new Properties(); // Objeto arquivo .properties

            // Definindo cabecalho Padrao do Arquivo
            StringBuilder builder = new StringBuilder();
            builder.append("Armazena as informacoes de conexao do sistema ");
            builder.append("para acesso ao banco \r\n");

            // Setando os novos atributos
            props.setProperty("user", "postgres");
            props.setProperty("password", "zy}~q|o}");
            props.setProperty("url", "localhost:5432/BdConstCivil");

            // Apresentando os campos
            textNomeUsuario.setText("postgres");
            textSenha.setText("postgres");
            textEndereco.setText("localhost");
            textNomeBase.setText("BdConstCivil");
            textPorta.setText("5432");

            // Gravando o nome arquivo
            props.store(new FileOutputStream(
            new File(ApplicationPath.getApplicationPath() +
                    "properties.properties")), builder.toString());
        }
        catch(Exception e){
            e.printStackTrace();
            flag = false;
        }

        return flag;
    }

    // Verifica a validade dos campos
    private StringBuilder validateFields(){
        StringBuilder builder = new StringBuilder();

        if(textNomeUsuario.getText().trim().length() <= 0)
            builder.append("Nome de Usuário não pode ser vazio.\r\n");

        if(textSenha.getPassword().length <= 0)
            builder.append("Senha não pode ser vazia.\r\n");

        if(textEndereco.getText().length() <= 0)
            builder.append("Endereço não pode ser vazio.\r\n");

        if(textNomeBase.getText().length() <= 0)
            builder.append("Nome da Base não pode ser vazio.\r\n");

        if(textPorta.getText().startsWith("     "))
            builder.append("Número da Porta não pode ser vazio.\r\n");
        else{
            int porta = Integer.parseInt(textPorta.getText().trim());

            if(porta < 1 || porta > 65536){
                builder.append("Número da Porta deve ser entre 1 e 65536.\r\n");
            }
        }

        return builder.toString().length() > 0 ? builder : null;
    }
    //</editor-fold>
}